next up previous contents index
Next: The Delphi approach Up: Objects Previous: Objects

The Turbo Pascal approach

In the Turbo Pascal approach, Objects should be treated as a special kind of record. The record contains all the fields that are declared in the objects definition, and pointers to the methods that are associated to the objects' type.

An object is declared just as you would declare a record; except that you can now declare procedures and fuctions as of they were part of the record.

Objects can ''inherit'' fields and methods from ''parent'' objects. This means that you can use these fields and methods as if the were included in the objects you declared as a ''child'' object.

Furthermore, you can declare fields, procedures and functions as public or private. By default, fields and methods are public, and are exported outside the current unit. Fields or methods that are declared private are only accessible in the current unit.

The prototype declaration of an object is as follows :

TObj = Object [(ParentObjectType)]
  [Constructor ConstructorName;]
  [Destructor DestructorName;]
  Field1 : Type1;
  ...
  Fieldn : Typen;
  Method1;
  Method2;
  [private
  PrField1 : PrType1;
  ...
  PrFieldn : PrTypen;
  PrMethod1;
  ...
  PrMethodn;]
  [public
  PuField1 : PuType1;
  ..
  Pufield1 : PuTypen;
  PuMethod1;
  ...
  PuMethodn;]
  end;
You can repeat as many private and public blocks as you want. Methods are normal function or procedure declarations.

As can be seen in the prototype object declaration, Free Pascal supports constructors and destructors. You are responsible for calling the destructor and constructor explicitly when using objects.

Free Pascal supports also the extended syntax of the New and Dispose procedures. In case you want to allocate a dynamic varible of an object type, you can specify the constructor's name in the call to New. The New is implemented as a function which returns a pointer to the instantiated object. Given the following declarations :

Type
  TObj = object;
   Constructor init;
   ...
   end;
  Pobj = ^TObj;

Var PP : Pobj;
Then the following 3 calls are equivalent :
 pp:=new (Pobj,Init);
and
  new(pp,init);
and also
  new (pp);
  pp^.init;
In the last case, the compiler will issue a warning that you should use the extended syntax of new and dispose to generate instances of an object. You can ignore this warning, but it's better programming practice to use the extended syntax to create instances of an object.

Similarly, the Dispose procedure accepts the name of a destructor. The destructor will then be called, before removing the object from the heap.

In view of the compiler warning remark, the now following Delphi approach may be considered a more natural way of object-oriented programming.


next up previous contents index
Next: The Delphi approach Up: Objects Previous: Objects

Michael Van Canneyt
Tue Mar 31 16:48:49 CEST 1998